//
//  42_接雨水.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/3/10.
/**
 https://leetcode.cn/problems/trapping-rain-water/description/
 
 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。
 输入：height = [0,1,0,2,1,0,1,3,2,1,2,1]
 输出：6
 解释：上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图，在这种情况下，可以接 6 个单位的雨水（蓝色部分表示雨水）。
 示例 2：

 输入：height = [4,2,0,3,2,5]
 输出：9
 */

import UIKit
//
class JieYuShui: NSObject {
    
    func QA() {
        let result = trap([0,1,0,2,1,0,1,3,2,1,2,1])
        print(result) // 6
        print(trap([4,2,0,3,2,5])) // 9

    }
    
    
    // 空间O(1) 时间 O(n) 最有接
    func trap(_ height: [Int]) -> Int {
        if height.count < 2 {
            return 0
        }
        var water = 0, l = 0, r = height.count - 1
        var lowerMax = 0
        while l < r {
            let lower = min(height[l], height[r])
            lowerMax = max(lower, lowerMax)
            water += lowerMax - lower
            if height[l] <= height[r] {
                l += 1
            } else {
                r -= 1
            }
        }
        return water
    }
    
    // min(左边最高，右边最高) 如果这个值大于 当前柱子，水 = min - height[i]
    func trap1(_ height: [Int]) -> Int {
        if height.count < 2 {
            return 0
        }

        var leftMax = Array(repeating: 0, count: height.count)
        
        for i in 1..<height.count {
            leftMax[i] = max(leftMax[i - 1], height[i - 1])
        }

        var rightMax = Array(repeating: 0, count: height.count)
        for i in (0..<height.count - 1).reversed() {
            rightMax[i] = max(rightMax[i + 1], height[i + 1])
        }
        
        var water = 0
        for (index, item) in height.enumerated() {
            let min = min(leftMax[index], rightMax[index])
            if min <= item  {
                continue
            }
            water = water + (min - item)
        }
        
        return water
    }
}
